import { useLocation, useParams } from "react-router-dom";
import { createHashHistory } from "history";

function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
  var r = window.location.href.split("?")[1]
    ? window.location.href.split("?")[1].match(reg)
    : window.location.search.substring(1).match(reg);
  var q = window.location.pathname.substring(1).match(reg_rewrite);

  if (r != null) {
    return typeof r === "string" ? r : decodeURIComponent(r[2]);
  } else if (q != null) {
    return decodeURIComponent(q[2]);
  } else {
    return null;
  }
}

export const withRouter = (Component) => {
  const Wrapper = (props) => {
    const history = createHashHistory(); //useHistory();
    const location = useLocation();
    const params = useParams();
    history.get = (name) => getQueryString(name);
    return (
      <Component
        history={history}
        location={location}
        params={params}
        {...props}
      />
    );
  };

  return Wrapper;
};
